package com.example.terminalservice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.terminalservice.common.CodeEnum;
import com.example.terminalservice.common.Result;
import com.example.terminalservice.exception.MyException;
import com.example.terminalservice.mapper.UserRoleMapper;
import com.example.terminalservice.pojo.Role;
import com.example.terminalservice.service.RoleService;
import com.example.terminalservice.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 28142
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2023-08-05 09:42:19
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Result getRolesByUser(Integer userId) {
        return Result.success(roleMapper.getRolesByUser(userId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean setRolesByUser(Integer userId, List<Integer> ids) {
        if (ids.size() == 0) {
            throw new MyException(CodeEnum.CODE_401.getCode(), "请至少选择一个角色");
        }
        // 删除当前角色列表
        userRoleMapper.deleteByUserId(userId);
        // 批量插入
        userRoleMapper.insertBatch(userId, ids);
        return true;
    }

    @Override
    public Result findPage(Integer pageNum, Integer pageSize, String name) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(name), Role::getName, name);
        Page<Role> page = new Page<>(pageNum, pageSize);
        return Result.success(roleMapper.selectPage(page, wrapper));
    }

    @Override
    public boolean saveRole(Role role) {
        // 获取当前用户身份验证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果id为null，表示新增；否则是修改
        if (role.getId() == null) {
            if (!authentication.getAuthorities().contains(new SimpleGrantedAuthority("sys:role:add"))) {
                throw new AccessDeniedException("抱歉，您不具备添加角色的权限");
            }
            // 根据唯一编码查询角色
            LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Role::getFlag, role.getFlag());
            Role one = roleMapper.selectOne(wrapper);
            // 唯一编码已存在，抛异常
            if (one != null) {
                throw new MyException(CodeEnum.CODE_401.getCode(), "唯一编码已存在");
            }
        } else {
            if (!authentication.getAuthorities().contains(new SimpleGrantedAuthority("sys:role:update"))) {
                throw new AccessDeniedException("抱歉，您不具备修改角色的权限");
            }
        }
        return saveOrUpdate(role);
    }
}




